<template>
  <!-- 病历 -->
  <view class="page">
    <!-- 日历 -->
    <!-- <view class="calendarBox">

			<image src="/static/my/calendar.png" mode="aspectFit"></image>
		</view> -->
    <!-- 基本信息 -->
    <view class="basicInfoBox">
      <view class="topBasicBox">
        <view class="leftBasicBox">
          <image
            v-if="BasicData.author"
            :src="BasicData.author"
            mode="aspectFit"
          ></image>
          <view class="noPetImg" v-else> 暂无宠物图片 </view>
        </view>

        <view class="rightBasicBox">
          <view class="disspb borderBottom">
            <view class="title"> 基本信息 </view>

            <image
              class="editImg"
              @click="goPages()"
              src="/static/my/editText.png"
              mode="widthFix"
            ></image>
          </view>
          <view class="disspb borderBottom">
            <text class="label"> 姓名： </text>
            <input
              type="text"
              class="value"
              disabled
              v-model="BasicData.name"
              placeholder-style="font-weight: 400;font-size: 24rpx;color: #bbbbbb;"
            />
          </view>
          <view class="disspb borderBottom">
            <text class="label"> 性别： </text>
            <view class="">{{ BasicData.gender == 1 ? "公" : "母" }}</view>
          </view>
          <view class="disspb borderBottom">
            <text class="label"> 年龄： </text>
            <input
              type="text"
              class="value"
              disabled
              v-model="BasicData.age"
              placeholder-style="font-weight: 400;font-size: 24rpx;color: #bbbbbb;"
            />
          </view>
          <view class="disspb borderBottom">
            <text class="label"> 出生日期： </text>
            <uni-datetime-picker
              class="form-picker"
              type="date"
              disabled
              v-model="BasicData.birthDate"
              @change="changeLog"
              :border="false"
              :clear-icon="false"
            />
          </view>
          <view class="disspb borderBottom">
            <text class="label"> 品种： </text>
            <input
              type="text"
              class="value"
              disabled
              v-model="BasicData.breed"
              placeholder-style="font-weight: 400;font-size: 24rpx;color: #bbbbbb;"
            />
          </view>
        </view>
      </view>

      <view class="botBasicBox">
        <view class="disspb borderBottom">
          <text class="label"> 主人姓名： </text>
          <input
            type="text"
            class="value"
            disabled
            v-model="BasicData.fullName"
            placeholder-style="font-weight: 400;font-size: 24rpx;color: #bbbbbb;"
          />
        </view>

        <view class="disspb borderBottom">
          <text class="label"> 联系电话： </text>
          <input
            type="text"
            class="value"
            disabled
            v-model="BasicData.tel"
            placeholder-style="font-weight: 400;font-size: 24rpx;color: #bbbbbb;"
          />
        </view>

        <view class="disspb borderBottom">
          <text class="label"> 家庭住址： </text>
          <input
            type="text"
            class="value"
            disabled
            v-model="BasicData.address"
            placeholder-style="font-weight: 400;font-size: 24rpx;color: #bbbbbb;"
          />
        </view>

        <view class="disspb borderBottom">
          <text class="label"> 宠物体重： </text>
          <view class="">{{ BasicData.weight }} KG</view>
        </view>

        <view class="disspb borderBottom">
          <text class="label"> 是否绝育： </text>
          <view class="">{{ BasicData.isSpayed == 0 ? "否" : "是" }}</view>
        </view>

        <view class="disspb borderBottom">
          <text class="label"> 疫苗情况： </text>
          <view class="">{{ BasicData.vaccineSituation }}</view>
        </view>
      </view>
    </view>

    <!-- 就诊记录 -->
    <view class="consultationBox">
      <view class="title"> 就诊记录 </view>
      <view class="consultationList">
        <view
          class="consultationItem"
          v-for="(item, index) in consultationLIst"
          :key="index"
        >
          <view class="scImg">
            <!-- 只有已保存的记录（有id）才显示编辑按钮 -->
            <image
              v-if="!!item.id"
              @click="xgBtn(item, index)"
              src="/static/image/edit_icon@2x.png"
              mode=""
            ></image>
            <image
              style="margin-left: 20rpx"
              class=""
              @click="scBtn(item, index)"
              src="/static/activity/icon_sc.png"
              mode=""
            ></image>
          </view>

          <view class="disspb borderBottom">
            <text class="label"> 日期： </text>
            <uni-datetime-picker
              class="form-picker"
              type="date"
              placeholder="点击选择"
              v-model="item.visitDate"
              @change="changeLog"
              :border="false"
              :clear-icon="false"
              :disabled="!!item.id"
            />
          </view>
          <view class="disspb borderBottom">
            <text class="label"> 事项： </text>
            <input
              type="text"
              class="value"
              placeholder="点击填写"
              v-model="item.visitItem"
              :disabled="!!item.id"
              placeholder-style="font-weight: 400;font-size: 24rpx;color: #bbbbbb;"
            />
          </view>

          <view class="disspb borderBottom">
            <text class="label"> 治疗时间： </text>
            <input
              type="text"
              class="value"
              placeholder="点击填写"
              v-model="item.treatmentDuration"
              :disabled="!!item.id"
              placeholder-style="font-weight: 400;font-size: 24rpx;color: #bbbbbb;"
            />
          </view>

          <view class="disspb borderBottom">
            <text class="label"> 治疗过程： </text>
            <input
              type="text"
              class="value"
              placeholder="点击填写"
              v-model="item.treatmentProcess"
              :disabled="!!item.id"
              placeholder-style="font-weight: 400;font-size: 24rpx;color: #bbbbbb;"
            />
          </view>

          <view class="disspb borderBottom">
            <text class="label"> 特殊情况说明： </text>
            <textarea
              class="custom-textarea"
              auto-height
              placeholder="点击填写"
              v-model="item.specialNotes"
              :disabled="!!item.id"
              placeholder-style="font-weight: 400;font-size: 24rpx;color: #bbbbbb;"
            ></textarea>
          </view>
        </view>
      </view>
    </view>
    <!-- 添加病历 -->
    <view class="addConsultationBox" @click="addConsultation">
      <image src="/static/my/addBingli.png" mode="aspectFit"></image>
    </view>

    <view class="saveBtn">
      <button @click="save">保存</button>
    </view>
    <uni-popup ref="popup" type="center" border-radius="10px 10px 0 0">
      <view class="e-consultationList">
        <view class="consultationItem">
          <view class="e-bing"> 编辑病例 </view>
          <view class="disspb borderBottom">
            <text class="label"> 日期： </text>
            <uni-datetime-picker
              class="form-picker"
              type="date"
              placeholder="点击选择"
              v-model="editData.visitDate"
              @change="changeLog"
              :border="false"
              :clear-icon="false"
            />
          </view>
          <view class="disspb borderBottom">
            <text class="label"> 事项： </text>
            <input
              type="text"
              class="value"
              placeholder="点击填写"
              v-model="editData.visitItem"
              placeholder-style="font-weight: 400;font-size: 24rpx;color: #bbbbbb;"
            />
          </view>

          <view class="disspb borderBottom">
            <text class="label"> 治疗时间： </text>
            <input
              type="text"
              class="value"
              placeholder="点击填写"
              v-model="editData.treatmentDuration"
              placeholder-style="font-weight: 400;font-size: 24rpx;color: #bbbbbb;"
            />
          </view>

          <view class="disspb borderBottom">
            <text class="label"> 治疗过程： </text>
            <input
              type="text"
              class="value"
              placeholder="点击填写"
              v-model="editData.treatmentProcess"
              placeholder-style="font-weight: 400;font-size: 24rpx;color: #bbbbbb;"
            />
          </view>

          <view class="disspb borderBottom">
            <text class="label"> 特殊情况说明： </text>
            <textarea
              class="custom-textarea"
              auto-height
              placeholder="点击填写"
              v-model="editData.specialNotes"
              placeholder-style="font-weight: 400;font-size: 24rpx;color: #bbbbbb;"
            ></textarea>
          </view>
        </view>
        <view class="editSumit" @click="editSumit"> 确认修改 </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import commonMixin from "@/mixin/commonMinxin";

export default {
  mixins: [commonMixin],
  data() {
    return {
      editData: {},
      BasicData: {
        author: "",
        name: "",
        gender: "",
        age: "",
        birthTime: "",
        varieties: "",
        fullName: "",
        tel: "",
        address: "",
        pegWeight: "",
        isNeuter: "",
        isVaccin: "",
      },
      consultationLIst: [],
      offset: 1,
      total: 0, // 总数据条数
      hasMore: true, // 是否还有更多数据
    };
  },
  onLoad(options) {
    if (options.petId) {
      this.petId = options.petId;
    }
    this.getData();
    this.recodInit();
  },
  onReachBottom(e) {
    //nvue暂不支持滚动监听，可用bindingx代替
    if (this.hasMore) {
      this.offset++;
      this.recodInit();
    }
  },
  methods: {
    // 验证字段是否为空的辅助函数
    isEmpty(value) {
      if (!value) return true;
      if (typeof value === "string") {
        return value.trim() === "";
      }
      return false;
    },

    editSumit() {
      // 验证必填字段
      if (this.isEmpty(this.editData.visitDate)) {
        this.ts("请填写就诊日期");
        return;
      }
      if (this.isEmpty(this.editData.visitItem)) {
        this.ts("请填写事项");
        return;
      }
      if (this.isEmpty(this.editData.treatmentDuration)) {
        this.ts("请填写治疗时间");
        return;
      }
      if (this.isEmpty(this.editData.treatmentProcess)) {
        this.ts("请填写治疗过程");
        return;
      }
      if (this.isEmpty(this.editData.specialNotes)) {
        this.ts("请填写特殊情况说明");
        return;
      }

      uni.app.post(
        "/pet/visitRecords/updateVisitRecords",
        {
          id: this.editData.id,
          petId: this.petId,
          userId: uni.getStorageSync("userId"),
          visitDate: this.editData.visitDate,
          visitItem: this.editData.visitItem,
          treatmentDuration: this.editData.treatmentDuration,
          treatmentProcess: this.editData.treatmentProcess,
          specialNotes: this.editData.specialNotes,
        },
        "json",
        "",
        (res) => {
          if (res.code == 2000) {
            this.ts("修改成功");
            // 更新列表中的数据
            if (this.editData.index !== undefined) {
              this.consultationLIst[this.editData.index] = {
                ...this.consultationLIst[this.editData.index],
                visitDate: this.editData.visitDate,
                visitItem: this.editData.visitItem,
                treatmentDuration: this.editData.treatmentDuration,
                treatmentProcess: this.editData.treatmentProcess,
                specialNotes: this.editData.specialNotes,
              };
            }
            this.$refs.popup.close();
            // this.BasicData = res.data.records[0]
            // this.BasicData.author=this.BasicData.mediaList[0]
          }
        },
      );
    },
    goPages() {
      // uni.navigateTo({
      // 	url: `/pages/my/editPetProfile?petId=${this.BasicData.id}&token=${uni.getStorageSync("token")}&userId=${uni.getStorageSync("userId")}`
      // })
      // return;
      let b = {
        hideNavBar: "0",
        hideTotalNavBar: "0",
        hideBottomSafeBar: "0",
        navtitle: "编辑宠物档案",
        url: `https://www.yaozhuasocial.com/yaozhua_shequ/#/pages/my/editPetProfile?petId=${this.BasicData.id}&token=${uni.getStorageSync("token")}&userId=${uni.getStorageSync("userId")}`,
      };
      this.fn(b);
      return;
    },
    fn(data) {
      switch (uni.getSystemInfoSync().platform) {
        case "android":
          let ddd = data;
          let d = JSON.stringify(ddd);
          console.log(d, "都是对的");
          window.AndroidBridge.pushNewWebVC(d);
          console.log("运行Android上");
          break;
        case "ios":
          window.webkit.messageHandlers.pushNewWebVC.postMessage(data);
          break;
        default:
          console.log("运行在开发者工具上");
          break;
      }
    },
    xgBtn(item, index) {
      this.editData = JSON.parse(JSON.stringify(item));
      this.editData.index = index; // 保存索引用于后续更新
      this.$refs.popup.open();
    },

    scBtn(item, index) {
      // if (this.consultationLIst.length == 1) {
      //   this.ts("不能再删了");
      //   return;
      // }
      let that = this;

      uni.showModal({
        title: "温馨提示",
        content: "确定删除此条记录?",
        success: function (res) {
          if (res.confirm) {
            that.okSC(item, index);
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
    },
    okSC(item, index) {
      // this.consultationLIst.splice(index,1)
      if (!item.id) {
        this.consultationLIst.splice(index, 1);
        return;
      }
      uni.app.post(
        "/pet/visitRecords/delVisitRecords",
        {
          id: item.id,
          petId: this.petId,
          userId: uni.getStorageSync("userId"),
        },
        "json",
        "",
        (res) => {
          if (res.code == 2000) {
            this.ts("删除成功");
            // 重置 offset 和 hasMore，重新加载数据
            this.offset = 1;
            this.hasMore = true;
            this.recodInit();
            // this.BasicData = res.data.records[0]
            // this.BasicData.author=this.BasicData.mediaList[0]
          }
        },
      );
    },

    save() {
      let flag = true;
      let newAD = [];

      // 基本信息验证
      if (!this.BasicData.name || this.BasicData.name.trim() === "") {
        this.ts("请填写宠物姓名");
        flag = false;
        return;
      }

      if (!this.BasicData.gender && this.BasicData.gender !== 0) {
        this.ts("请选择宠物性别");
        flag = false;
        return;
      }

      if (
        !this.BasicData.age ||
        this.BasicData.age === "" ||
        this.BasicData.age <= 0
      ) {
        this.ts("请填写宠物年龄");
        flag = false;
        return;
      }

      if (!this.BasicData.birthDate || this.BasicData.birthDate.trim() === "") {
        this.ts("请选择宠物出生日期");
        flag = false;
        return;
      }

      if (!this.BasicData.breed || this.BasicData.breed.trim() === "") {
        this.ts("请填写宠物品种");
        flag = false;
        return;
      }

      // 主人姓名、联系电话、家庭住址不做必填校验
      // if (!this.BasicData.fullName || this.BasicData.fullName.trim() === '') {
      //   this.ts("请填写主人姓名");
      //   flag = false;
      //   return;
      // }
      //
      // if (!this.BasicData.tel || this.BasicData.tel.trim() === '') {
      //   this.ts("请填写联系电话");
      //   flag = false;
      //   return;
      // }
      //
      // if (!this.BasicData.address || this.BasicData.address.trim() === '') {
      //   this.ts("请填写家庭住址");
      //   flag = false;
      //   return;
      // }

      if (
        !this.BasicData.weight ||
        this.BasicData.weight === "" ||
        this.BasicData.weight <= 0
      ) {
        this.ts("请填写宠物体重");
        flag = false;
        return;
      }

      if (!this.BasicData.isSpayed && this.BasicData.isSpayed !== 0) {
        this.ts("请选择是否绝育");
        flag = false;
        return;
      }

      if (
        !this.BasicData.vaccineSituation ||
        this.BasicData.vaccineSituation.trim() === ""
      ) {
        this.ts("请填写疫苗情况");
        flag = false;
        return;
      }

      // 就诊记录验证
      for (var i = 0; i < this.consultationLIst.length; i++) {
        console.log(
          this.consultationLIst[i].specialNotes,
          ";this.consultationLIst[i].specialNotes",
        );
        if (this.consultationLIst[i].visitDate == "") {
          this.ts("请填写就诊日期");
          flag = false;
        } else if (this.consultationLIst[i].visitItem == "") {
          this.ts("请填写事项");
          flag = false;
        } else if (this.consultationLIst[i].treatmentDuration == "") {
          this.ts("请填写治疗时间");
          flag = false;
        } else if (this.consultationLIst[i].treatmentProcess == "") {
          this.ts("请填写治疗过程");
          flag = false;
        } else if (this.consultationLIst[i].specialNotes == "") {
          this.ts("请填写特殊情况说明");
          flag = false;
        }
      }
      if (flag == false) {
        return;
      }
      this.consultationLIst.map((rrr) => {
        rrr.userId = uni.getStorageSync("userId");
        rrr.petId = this.petId;
        // 新增的
        if (!rrr.id) {
          newAD.push(rrr);
        }
      });

      uni.app.post(
        "/pet/visitRecords/addBatchVisitRecords",
        {
          visitRecordsList: newAD,
        },
        "json",
        "",
        (res) => {
          if (res.code == 2000) {
            console.log(res);
            uni.showToast({
              title: "保存成功",
              icon: "success",
            });
            // 调用 app 的 backevent 方法返回上一页
            this.goBack();
            // this.BasicData = res.data.records[0]
          }
        },
      );
    },
    recodInit() {
      uni.app.post(
        "/pet/visitRecords/getVisitRecords",
        {
          // id:
          petId: this.petId,
          userId: uni.getStorageSync("userId"),
          limit: 10,
          offset: this.offset,
        },
        "json",
        "",
        (res) => {
          if (res.code == 2000) {
            // 如果是第一页，重置数据
            if (this.offset === 1) {
              this.consultationLIst = res.data.records;
            } else {
              this.consultationLIst = this.consultationLIst.concat(
                res.data.records,
              );
            }

            // 更新总数和判断是否还有更多数据
            this.total = res.data.total || 0;
            const currentDataCount = this.consultationLIst.length;
            this.hasMore = currentDataCount < this.total;

            // this.BasicData = res.data.records[0]
            // this.BasicData.author=this.BasicData.mediaList[0]
          }
        },
      );
    },
    getData() {
      // 获取上面信息
      uni.app.post(
        "/pet/info/getInfos",
        {
          id: this.petId,
          userId: uni.getStorageSync("userId"),
          limit: 1,
          offset: 1,
        },
        "json",
        "",
        (res) => {
          if (res.code == 2000) {
            this.BasicData = res.data.records[0];
            this.BasicData.author = this.BasicData.mediaList[0];
          }
        },
      );
      // 获取宠物记录
      // {
      //   "id": 0,

      //   "petId": 0,

      // }
    },
    ts(tit) {
      uni.showToast({
        title: tit,
        icon: "none",
        duration: 2000,
      });
    },

    addConsultation() {
      // this.editData={}
      // this.$refs.popup.open()
      // return;
      let Item = {
        visitDate: "",
        visitItem: "",
        treatmentDuration: "",
        treatmentProcess: "",
        specialNotes: "",
      };
      this.consultationLIst.push(Item);
    },
    goBack() {
      switch (uni.getSystemInfoSync().platform) {
        case "android":
          window.AndroidBridge.backEvent();
          console.log("运行Android上");
          break;
        case "ios":
          window.webkit.messageHandlers.backEvent.postMessage({});
          break;
        default:
          console.log("运行在开发者工具上");
          uni.navigateBack({
            delta: 1,
          });
          break;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.noPetImg {
  height: 100%;
  font-size: 22rpx;
  width: 100%;
  display: flex;
  align-items: center;
}

.editSumit {
  width: 100%;
  background: #daf600;
  color: #333;
  line-height: 80rpx;
  border-radius: 100rpx;
  margin: 40rpx 0;
  text-align: center;
}

.e-consultationList {
  background: #ffffff;
  width: 80%;
  margin: 0 auto;
  padding: 40rpx;
  border-radius: 20rpx;

  .e-bing {
    text-align: center;
    line-height: 80rpx;
    font-weight: 550;
    font-size: 28rpx;
  }
}

.scImg {
  text-align: right;

  image {
    width: 40rpx;
    height: 40rpx;
  }
}

.page {
  background-color: #f8f8f8;
  padding-bottom: 60rpx;
}

.custom-textarea {
  // width: 100%;
  // height: 100px;
  /* 可以根据需要设置高度 */
  border: none;
  /* 取消默认边框 */
  background-color: transparent;
  /* 取消默认背景 */
  padding: 0;
  /* 取消默认内边距 */
  margin: 0;
  /* 取消默认外边距 */
  // line-height: 1.5;
  /* 设置行高 */
  color: #333;
  /* 设置字体颜色 */
  resize: none;
  /* 禁止用户手动调整大小 */
  overflow: hidden;
  /* 隐藏滚动条 */
  text-align: right;
  font-weight: bold;
  font-size: 26rpx;
  color: #303030;
}

.disspb {
  display: flex;
  // align-items: center;
  justify-content: space-between;
  padding: 15rpx 0;

  input {
    flex: 1;
    border-radius: 5rpx;
  }

  .label {
    font-weight: 500;
    font-size: 24rpx;
    color: #7f7f7f;
    white-space: nowrap;
  }

  .value {
    font-weight: bold;
    font-size: 26rpx;
    color: #303030;
    text-align: right;
  }
}

.borderBottom {
  border-bottom: 2rpx solid #f8f8f8;
}

.borderTop {
  border-top: 2rpx solid #f8f8f8;
}

.calendarBox {
  margin: 32rpx 28rpx;
  height: 80rpx;
  background-color: #ffffff;

  image {
    width: 100%;
    height: 100%;
  }
}

.basicInfoBox {
  margin: 32rpx 28rpx;
  padding: 32rpx;
  background-color: #ffffff;

  .topBasicBox {
    display: flex;
    justify-content: space-between;

    .leftBasicBox image {
      width: 300rpx;
      height: 402rpx;
      border-radius: 16rpx 16rpx 16rpx 16rpx;
    }

    .rightBasicBox {
      margin-left: 36rpx;

      .title {
        width: 120rpx;
        height: 42rpx;
        font-family:
          PingFang SC,
          PingFang SC;
        font-weight: bold;
        font-size: 30rpx;
        color: #303030;
        line-height: 40rpx;

        font-style: normal;
        text-transform: none;
      }

      .editImg {
        width: 78.96rpx;
        height: 34rpx;
      }
    }
  }
}

.consultationBox {
  margin: 32rpx 28rpx;

  .title {
    font-weight: bold;
    font-size: 30rpx;
    color: #303030;
    margin: 0 0 16rpx 32rpx;
  }

  .consultationList {
    .consultationItem {
      background-color: #ffffff;
      padding: 32rpx;
      margin-bottom: 32rpx;
    }
  }
}

.addConsultationBox {
  margin: 32rpx 28rpx 80rpx;
  height: 64rpx;
  border-radius: 16rpx 16rpx 16rpx 16rpx;

  image {
    width: 100%;
    height: 100%;
  }
}

.saveBtn {
  background: #ffffff;
  position: fixed;
  width: 100%;
  bottom: 0;
  padding: 20rpx 0;

  button {
    width: 90%;
    height: 60rpx;
    line-height: 60rpx;
    border: none;
    border-radius: 50px;
    background: #daf600;
  }
}
</style>
